<template>
  <el-container style="height: 100vh; flex-direction: column;">
    <!-- 顶部导航栏独占一行 -->
    <el-header class="main-header">
      <div class="header-left">
        <i class="el-icon-school"></i>
        <span class="system-title">选课管理系统</span>
      </div>
      <div class="header-right">
        <!-- 用户信息下拉菜单 -->
        <el-dropdown @command="handleUserCommand" trigger="hover">
          <span class="user-dropdown">
            <el-avatar :size="32" class="user-avatar">
              {{ userName.charAt(0).toUpperCase() }}
            </el-avatar>
            <span class="user-name">{{ userName }}</span>
            <i class="el-icon-arrow-down"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="profile">
              <span class="dropdown-item-content"><i class="el-icon-user"></i>个人信息</span>
            </el-dropdown-item>
            <el-dropdown-item command="password">
              <span class="dropdown-item-content"><i class="el-icon-key"></i>修改密码</span>
            </el-dropdown-item>
            <el-dropdown-item divided command="logout">
              <span class="dropdown-item-content"><i class="el-icon-switch-button"></i>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-header>
    <el-container style="height:calc(100vh - 60px);">
      <!-- 左侧菜单栏 -->
      <el-aside width="200px" style="background: #324157; color: #fff;">
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          background-color="#324157"
          text-color="#fff"
          active-text-color="#ffd04b"
          router
        >
          <el-menu-item index="/home">
            <i class="el-icon-house"></i>
            <span slot="title">{{ homeMenuTitle }}</span>
          </el-menu-item>
          <el-menu-item v-for="m in visibleMenus" :key="m.index" :index="m.index">
            <i :class="m.icon"></i>
            <span slot="title">{{ m.label }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <!-- 右侧内容区 -->
      <el-main style="background:#f5f6fa;">
        <router-view/>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { logout } from '@/api'

export default {
  data() {
    return {
      activeMenu: this.$route.path,
      userName: 'Admin'
    }
  },
  computed: {
    homeMenuTitle() {
      const t = this.$store.state.user.userType
      if (t === 1) return '学生首页'
      if (t === 2) return '教师首页'
      if (t === 3) return '管理员首页'
      return '首页'
    },
    visibleMenus() {
      const userType = this.$store.state.user.userType
      const permissions = this.$store.state.user.permissions || []
      const isSuperAdmin = this.$store.getters['user/isSuperAdmin']
      if (process.env.NODE_ENV !== 'production') {
        console.log('[menu-debug] userType=', userType, 'permissions=', permissions, 'isSuperAdmin=', isSuperAdmin)
      }
      // 基础菜单定义（后台资源 + 角色自助）
      const menuDefs = [
        { index: '/department', label: '系管理', icon: 'el-icon-office-building', permission: 'dept' },
        { index: '/major', label: '专业管理', icon: 'el-icon-collection', permission: 'major' },
        { index: '/class', label: '班级管理', icon: 'el-icon-user', permission: 'class' },
        { index: '/student', label: '学生管理', icon: 'el-icon-user-solid', permission: 'student' },
        { index: '/teacher', label: '教师管理', icon: 'el-icon-s-custom', permission: 'teacher' },
        { index: '/course', label: '课程管理', icon: 'el-icon-notebook-2', permission: 'course' },
        { index: '/course-selection', label: '选课管理', icon: 'el-icon-edit', permission: 'selection' },
        { index: '/admin-manage', label: '管理员管理', icon: 'el-icon-setting', permission: 'admin' },
        // 学生自助
        { index: '/elective-courses', label: '选修课程', icon: 'el-icon-star-off', studentOnly: true },
        { index: '/student-courses', label: '学生课程', icon: 'el-icon-notebook-1', studentOnly: true },
        { index: '/student-timetable', label: '课表查询', icon: 'el-icon-date', studentOnly: true },
        { index: '/student-grades', label: '成绩查询', icon: 'el-icon-data-analysis', studentOnly: true },
        { index: '/student-profile', label: '信息维护', icon: 'el-icon-user', studentOnly: true },
        // 教师自助
        { index: '/teacher-courses', label: '授课查询', icon: 'el-icon-notebook-2', teacherOnly: true },
        { index: '/teacher-timetable', label: '教师课表', icon: 'el-icon-date', teacherOnly: true },
        { index: '/teacher-grade-entry', label: '成绩录入', icon: 'el-icon-edit-outline', teacherOnly: true }
      ]
      // 管理员逻辑（方案A）：管理员首页仅通过 /home 呈现，不在菜单再重复；严格按权限显示。
      if (userType === 3) {
        if (isSuperAdmin) {
            // 超级管理员：显示所有后台权限菜单（有 permission 标记的），不含学生/教师自助
            return menuDefs.filter(m => !m.studentOnly && !m.teacherOnly && m.permission)
        }
        // 普通管理员：仅显示自己拥有权限位对应的后台菜单（无权限=空菜单）
        const owned = new Set(permissions)
        const filtered = menuDefs.filter(m => !m.studentOnly && !m.teacherOnly && m.permission && owned.has(m.permission))
        return filtered
      }
      // 学生逻辑：显示所有 studentOnly + 白名单后台功能（前提有权限）
      if (userType === 1) {
        const whitelist = ['course','selection']
        return menuDefs.filter(m => m.studentOnly || (m.permission && whitelist.includes(m.permission) && permissions.includes(m.permission)))
      }
      // 教师逻辑：显示所有 teacherOnly + 白名单后台功能（前提有权限）
      if (userType === 2) {
        const whitelist = ['course','class','student']
        return menuDefs.filter(m => m.teacherOnly || (m.permission && whitelist.includes(m.permission) && permissions.includes(m.permission)))
      }
      return []
    }
  },
  watch: {
    '$route.path'(val) {
      this.activeMenu = val
    },
    // 动态监听权限变化（例如登录后异步写入）
    '$store.state.user.permissions': {
      handler() { this.$nextTick(()=>{ this.activeMenu = this.$route.path }) },
      deep: true
    }
  },
  mounted() {
    console.log('HomeView mounted - Auth status:', this.$store.state.user.loggedIn);
    this.getUserInfo()
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      const storeUser = this.$store.state.user.userInfo
      if (storeUser && storeUser.username) {
        this.userName = storeUser.username
        return
      }
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      this.userName = userInfo.username || this.userName || 'Admin'
    },
    
    // 使用 el-menu 的 router 模式自动跳转，这里不再手动 push，避免二次导航导致 Navigation cancelled 日志
    handleMenuSelect() {},
    
    // 处理用户下拉菜单
    handleUserCommand(command) {
      switch (command) {
        case 'profile':
          this.handleProfile()
          break
        case 'password':
          this.handleChangePassword()
          break
        case 'logout':
          this.handleLogout()
          break
      }
    },
    
    // 个人信息
    handleProfile() {
      this.$message.info('个人信息功能开发中...')
    },
    
    // 修改密码
    handleChangePassword() {
      this.$message.info('修改密码功能开发中...')
    },
    
    // 退出登录
    async handleLogout() {
      try {
        await this.$confirm('确定要退出登录吗？', '确认退出', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
        
        const loading = this.$loading({
          lock: true,
          text: '正在退出...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        try {
          // 调用退出接口
          await logout()
        } catch (error) {
          console.log('调用退出接口失败，但继续执行退出逻辑', error)
        }
        
        // 清除本地存储
        localStorage.removeItem('userInfo')
        localStorage.removeItem('token')
        localStorage.removeItem('isLoggedIn')
        
        // 更新store状态
        this.$store.commit('user/logout')
        
        loading.close()
        this.$message.success('退出成功')
        
  // 跳转到登录页（避免路由守卫冲突）
  window.location.replace('/login')
        
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('退出失败，请重试')
          console.error('退出登录失败:', error)
        }
      }
    },
    
    // 兼容旧的退出方法
    logout() {
      this.handleLogout()
    }
  }
}
</script>

<style scoped>
/* 主头部样式 */
.main-header {
  background: #2d3a4b;
  color: #fff;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.header-left {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: 600;
}

.header-left i {
  font-size: 28px;
  margin-right: 12px;
  color: #409eff;
}

.system-title {
  color: white;
}

.header-right {
  display: flex;
  align-items: center;
}

/* 用户下拉菜单 */
.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s;
  color: white;
}

.user-dropdown:hover {
  background: rgba(255, 255, 255, 0.1);
}

.user-avatar {
  margin-right: 8px;
  background: #409eff;
  border: 2px solid rgba(255, 255, 255, 0.2);
  color: white;
  font-weight: 600;
}

.user-name {
  margin-right: 8px;
  font-weight: 500;
  font-size: 14px;
}

/* 菜单样式 */
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 100%;
  border-right: none;
}

/* 下拉菜单项样式 */

/* 统一下拉菜单项内容对齐 */
:deep(.el-dropdown-menu__item) {
  padding: 10px 16px;
}
.dropdown-item-content {
  display: flex;
  align-items: center;
}
.dropdown-item-content i {
  margin-right: 8px;
  width: 16px;
  text-align: center;
}

:deep(.el-dropdown-menu__item:hover) {
  background: #f5f7fa;
  color: #409eff;
}

:deep(.el-dropdown-menu__item--divided) {
  border-top: none;
}

:deep(.el-dropdown-menu__item--divided::before) {
  background: transparent !important; /* 或改成更深的色，也可直接隐藏 */
  height: 0 !important;
  margin: 0 !important;
  content: none !important;
  display: none !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-header {
    padding: 0 16px;
  }
  
  .system-title {
    display: none;
  }
  
  .user-name {
    display: none;
  }
}
</style>